from django.shortcuts import *
from django.http import *
from .models import *


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')


def index(request):
    cont = Conten.objects.all()
    return render(request, 'index.html',{'cont':cont})


def logins(request):
    name = request.POST.get('name')
    pwd = request.POST.get('pwd')
    user = User.objects.filter(username=name, pwd=pwd).first()
    if user:
        request.session['user'] = user.username
        return JsonResponse({'data': 1})
    return JsonResponse({'data': 0, 'mag': '帐号密码错误'})


def add(request):
    if request.method == 'GET':
        user = User.objects.all()
        return render(request, 'add.html', {'user': user})
    else:
        tits = request.POST.get('tits')
        content = request.POST.get('content')
        zt = request.POST.get('zt')
        name = request.POST.get('name')
        add = Conten(tits=tits,content=content,zt=zt,name_id=name)
        add.save()
        return redirect(reverse('index'))


def update(request,cid):
    if request.method == 'GET':
        user = User.objects.all()
        cont = Conten.objects.filter(pk=cid).first()
        return render(request, 'update.html', {'user': user,'cont':cont})
    else:
        tits = request.POST.get('tits')
        content = request.POST.get('content')
        zt = request.POST.get('zt')
        time = request.POST.get('time')
        name = request.POST.get('name')
        Conten.objects.filter(pk=cid).update(tits=tits,time=time,content=content,zt=zt,name_id=name)
        return redirect(reverse('index'))

def delete(request):
    return None


def deleteall(request):
    if request.method == "POST":
        list = request.POST.getlist('list')
        for i in list:
            d = Conten.objects.get(pk=i)
            d.delete()
        return JsonResponse({'start':'成'})
    return redirect(reverse('index'))


def crea(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        if name:
            creall = Conten.objects.filter(tits__icontains=name)
            print(creall)
            list = []
            for i in creall:
                data = {
                    'id':i.id,
                    'tits':i.tits,
                    'content':i.content,
                    'zt':i.zt,
                    'time':i.time,
                    'name':i.name.username,
                }
                list.append(data)
            return JsonResponse(list,safe=False)